package com.wistech.commons.web.session;

import java.io.Serializable;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Map;

import javax.servlet.http.HttpSession;

import com.wistech.commons.utils.spring.SpringContextHolder;

public class CustomHttpSessionWrapper extends HttpSessionWrapper {
	private String sessionId = "";
	private SessionManager sessionManager;

	public CustomHttpSessionWrapper(String sessionId, HttpSession session) {
		super(session);
		this.sessionId = sessionId;
		sessionManager = (SessionManager) SpringContextHolder
				.getBean("sessionManager");
	}

	@Override
	public Object getAttribute(String arg0) {
		return sessionManager.getAttribute(sessionId, arg0);
	}

	@Override
	public Enumeration<String> getAttributeNames() {
		return sessionManager.getAttributeNames(sessionId);
	}

	@Override
	public void invalidate() {
		super.invalidate();
		sessionManager.removeSession(sessionId);
	}

	@Override
	public void removeAttribute(String arg0) {
		sessionManager.removeAttribute(sessionId, arg0);
	}

	@Override
	public void setAttribute(String arg0, Object arg1) {
		sessionManager.setAttribute(sessionId, arg0, arg1);
	}

	@SuppressWarnings({ "unchecked", "unused" })
	private boolean isSerializable(Object arg1) {
		if (!(arg1 instanceof Serializable)) {
			return false;
		}
		if (arg1 instanceof Map) {
			Map<Object, Object> map = (Map<Object, Object>) arg1;
			for (Map.Entry<Object, Object> entry : map.entrySet()) {
				if (!(entry.getKey() instanceof Serializable)
						|| !(entry.getValue() instanceof Serializable)) {
					return false;
				}
			}
		}

		if (arg1 instanceof Collection) {
			Collection<Object> collection = (Collection<Object>) arg1;
			for (Object element : collection) {
				if (!(element instanceof Serializable)) {
					return false;
				}
			}
		}
		return true;
	}

}
